/*
This file is part of vlc-remote.

vlc-remote is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

vlc-remote is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with vlc-remote.  If not, see <http://www.gnu.org/licenses/>.
*/
var _MILLISECOND = 1;
var _SECOND      = 1000 * _MILLISECOND;
var _MINUTE      = 60 * _SECOND;
var _HOUR        = 60 * _MINUTE;
var _DAY         = 24 * _HOUR;
var _WEEK        = 7 * _DAY;

var remote;

function preferString(first, second, third) {
    return (0 < first.length) ? first : (0 < second.length) ? second : third;
}

function _unescape(s) {
  s = s.replace(/&amp;/g, '&');
  s = s.replace(/&#39;/g, '\'');
  s = s.replace(/&quot;/g, '"');
  return s;
}

function _escape(s) {
    return s.replace(/\\/g, '\\\\');
}

function getListIconType(path) {
    var ret = "dir";
    if (-1 < path.indexOf(".")) {
        var ext = path.substr(path.lastIndexOf('.') + 1);
        switch (ext.toLowerCase()) {
        case "jpg":
        case "jpeg":
        case "gif":
        case "png":
        case "bmp":
            ret = "image";
            break;
        case "mp3":
        case "m4a":
        case "ogg":
        case "oga":
        case "wav":
        case "bmu":
        case "wma":
        case "flac":
        case "ra":
        case "ram":
        case "aac":
            ret = "audio";
            break;
        case "ram":
        case "avi":
        case "mpeg":
        case "mpg":
        case "mov":
        case "flv":
        case "mp4":
        case "m4v":
        case "wmv":
        case "mkv":
        case "ogv":
            ret = "video";
            break;
        default:
            ret = "file";
            if (4 < ext.length) ret = "dir";
            else if (-1 < ext.indexOf("flash")) ret = "video";
            break;
        }
    }
    return ret;
}

function _formatTime(milliseconds) {
    return _padLeft('' + Math.floor(milliseconds / _MINUTE), 1, '0') + 'm' + _padLeft('' + Math.floor((milliseconds / _SECOND) % 60), 2, '0') + 's';
}

function _padLeft(str, len, padChar) {
    if (!len) len = 2;
    if (!padChar) padChar = '0';
    if (str && str.length < len) return padChar + str;
    else return str;
}

function dropFavouritesTable() {
    var db = openDatabaseSync("VlcRemoteSettings", "1.0", "VlcRemoteSettings", 100);
    var update = "DROP TABLE IF EXISTS Favourites";
    db.transaction(function(tx) {
        tx.executeSql(update, data);
    });}

function saveFavourite(name, connection, path) {
    var db = openDatabaseSync("VlcRemoteSettings", "1.0", "VlcRemoteSettings", 100);
    var update = "INSERT INTO Favourites VALUES(?, ?, ?)";
    var data = [name, connection, path];
    db.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS Favourites(name TEXT, connection TEXT, path TEXT, PRIMARY KEY (name, connection) ON CONFLICT REPLACE)');
        tx.executeSql(update, data);
    });
}

function deleteFavourite(name, connection) {
    var db = openDatabaseSync("VlcRemoteSettings", "1.0", "VlcRemoteSettings", 100);
    var update = "DELETE FROM Favourites WHERE name=? AND connection=?";
    var data = [name, connection];
    db.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS Favourites(name TEXT, connection TEXT, path TEXT, PRIMARY KEY (name, connection) ON CONFLICT REPLACE)');
        tx.executeSql(update, data);
    });
}

function loadFavourite(name, connection) {
    var favourites = {}
    var db = openDatabaseSync("VlcRemoteSettings", "1.0", "VlcRemoteSettings", 100);
    var data = [name, connection];
    db.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS Favourites(name TEXT, connection TEXT, path TEXT, PRIMARY KEY (name, connection) ON CONFLICT REPLACE)');
        var rs = tx.executeSql('SELECT * FROM Favourites WHERE name=? AND connection=? ORDER BY connection ASC, name ASC LIMIT 1', data);
        favourites = rs.rows;
    });
    return favourites;
}

function loadFavouritesByConnection(connection) {
    var favourites = {}
    var db = openDatabaseSync("VlcRemoteSettings", "1.0", "VlcRemoteSettings", 100);
    var data = [connection];
    db.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS Favourites(name TEXT, connection TEXT, path TEXT, PRIMARY KEY (name, connection) ON CONFLICT REPLACE)');
        var rs = tx.executeSql('SELECT * FROM Favourites WHERE connection=? ORDER BY connection ASC, name ASC LIMIT 150', data);
        favourites = rs.rows;
    });
    return favourites;
}

function loadFavourites() {
    var favourites = {}
    var db = openDatabaseSync("VlcRemoteSettings", "1.0", "VlcRemoteSettings", 100);
    db.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS Favourites(name TEXT, connection TEXT, path TEXT, PRIMARY KEY (name, connection) ON CONFLICT REPLACE)');
        var rs = tx.executeSql('SELECT * FROM Favourites ORDER BY connection ASC, name ASC LIMIT 150');
        favourites = rs.rows;
    });
    return favourites;
}


function dropSettingsTable() {
    var db = openDatabaseSync("VlcRemoteSettings", "1.0", "VlcRemoteSettings", 100);
    var update = "DROP TABLE IF EXISTS Settings";
    db.transaction(function(tx) {
        tx.executeSql(update, data);
    });}

function saveSetting(name, connection, type, textField, integerField) {
    var db = openDatabaseSync("VlcRemoteSettings", "1.0", "VlcRemoteSettings", 100);
    var update = "INSERT INTO Settings VALUES(?, ?, ?, ?, ?)";
    var data = [name, connection, type, textField, integerField];
    //console.debug("settings save called: " + name + " " + integerField);
    db.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS Settings(name TEXT, connection TEXT, type TEXT, textField TEXT, integerField INTEGER, PRIMARY KEY (name, connection) ON CONFLICT REPLACE)');
        tx.executeSql(update, data);
    });
}

function deleteSetting(name, connection) {
    var db = openDatabaseSync("VlcRemoteSettings", "1.0", "VlcRemoteSettings", 100);
    var update = "DELETE FROM Settings WHERE name=? AND connection=?";
    var data = [name, connection];
    db.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS Settings(name TEXT, connection TEXT, type TEXT, textField TEXT, integerField INTEGER, PRIMARY KEY (name, connection) ON CONFLICT REPLACE)');
        tx.executeSql(update, data);
    });
}

function loadSetting(name, connection) {
    var connections = {}
    var db = openDatabaseSync("VlcRemoteSettings", "1.0", "VlcRemoteSettings", 100);
    var data = [name, connection];
    db.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS Settings(name TEXT, connection TEXT, type TEXT, textField TEXT, integerField INTEGER, PRIMARY KEY (name, connection) ON CONFLICT REPLACE)');
        var rs = tx.executeSql('SELECT * FROM Settings WHERE name=? AND connection=? ORDER BY connection ASC, name ASC LIMIT 1', data);
        connections = rs.rows;
    });
    return connections;
}

function loadSettingsByConnection(connection) {
    var connections = {}
    var db = openDatabaseSync("VlcRemoteSettings", "1.0", "VlcRemoteSettings", 100);
    var data = [connection];
    db.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS Settings(name TEXT, connection TEXT, type TEXT, textField TEXT, integerField INTEGER, PRIMARY KEY (name, connection) ON CONFLICT REPLACE)');
        var rs = tx.executeSql('SELECT * FROM Settings WHERE connection=? ORDER BY connection ASC, name ASC LIMIT 150', data);
        connections = rs.rows;
    });
    return connections;
}

function loadSettings() {
    var connections = {}
    var db = openDatabaseSync("VlcRemoteSettings", "1.0", "VlcRemoteSettings", 100);
    db.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS Settings(name TEXT, connection TEXT, type TEXT, textField TEXT, integerField INTEGER, PRIMARY KEY (name, connection) ON CONFLICT REPLACE)');
        var rs = tx.executeSql('SELECT * FROM Settings ORDER BY connection ASC, name ASC LIMIT 150');
        connections = rs.rows;
    });
    return connections;
}

function dropConnectionsTable() {
    var db = openDatabaseSync("VlcRemoteSettings", "1.0", "VlcRemoteSettings", 100);
    var update = "DROP TABLE IF EXISTS Connections";
    db.transaction(function(tx) {
        tx.executeSql(update, data);
    });}

function saveConnection(name, type, ipAddress, port, username, password, secured, datelastused) {
    var db = openDatabaseSync("VlcRemoteSettings", "1.0", "VlcRemoteSettings", 100);
    var update = "INSERT INTO Connections VALUES(?, ?, ?, ?, ?, ?, ?, ?)";
    var data = [name, type, ipAddress, port, username, password, secured, datelastused];
    db.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS Connections(name TEXT PRIMARY KEY ON CONFLICT REPLACE, type TEXT, ipAddress TEXT, port TEXT, username TEXT, password TEXT, secured BOOLEAN, dateLastUsed INTEGER)');
        tx.executeSql(update, data);
    });
}

function deleteConnection(name) {
    var db = openDatabaseSync("VlcRemoteSettings", "1.0", "VlcRemoteSettings", 100);
    var update = "DELETE FROM Connections WHERE name=?";
    var data = [name];
    db.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS Connections(name TEXT PRIMARY KEY ON CONFLICT REPLACE, type TEXT, ipAddress TEXT, port TEXT, username TEXT, password TEXT, secured BOOLEAN, dateLastUsed INTEGER)');
        tx.executeSql(update, data);
    });
}

function loadConnections() {
    var connections = {}
    var db = openDatabaseSync("VlcRemoteSettings", "1.0", "VlcRemoteSettings", 100);
    db.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS Connections(name TEXT PRIMARY KEY ON CONFLICT REPLACE, type TEXT, ipAddress TEXT, port TEXT, username TEXT, password TEXT, secured BOOLEAN, dateLastUsed INTEGER)');
        var rs = tx.executeSql('SELECT * FROM Connections ORDER BY dateLastUsed DESC LIMIT 50');
        connections = rs.rows;
    });
    return connections;
}

function timestampConnection(name) {
    var connections = {}
    var db = openDatabaseSync("VlcRemoteSettings", "1.0", "VlcRemoteSettings", 100);
    var update = "UPDATE Connections SET dateLastUsed=? WHERE name=?";
    var data = [Math.round(new Date().getTime() / 1000), name];
    db.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS Connections(name TEXT PRIMARY KEY ON CONFLICT REPLACE, type TEXT, ipAddress TEXT, port TEXT, username TEXT, password TEXT, secured BOOLEAN, dateLastUsed INTEGER)');
        tx.executeSql(update, data);
    });
}

function init(ipAddress) {
    remote = new VlcRemote.VlcRemote(ipAddress);
}

function remotePing() { return false; }
function remoteGetStatus() { if (remote) remote.requestStatus(); }
function remoteGetPlaylist() { if (remote) remote.requestPlaylist(); }
function remoteRequestTrackNext() { if (remote) remote.requestTrackNext(); }
function remoteRequestTrackPrevious() { if (remote) remote.requestTrackPrevious(); }
function remoteRequestStartPlayback() { if (remote) remote.requestStartPlayback(); }
function remoteRequestResumePlayback() { if (remote) remote.requestResumePlayback(); }
function remoteRequestStopPlayback() { if (remote) remote.requestStopPlayback(); }
function remoteRequestPausePlayback() { if (remote) remote.requestPausePlayback(); }
function remoteRequestToggleFullscreen() { if (remote) remote.requestToggleFullscreen(); }
function remoteRequestSetVolume(volume) { if (remote) remote.requestSetVolume(volume); }
function remoteRequestIncreaseVolume(increment) { if (remote) remote.requestIncreaseVolume(increment); }
function remoteRequestDecreaseVolume(increment) { if (remote) remote.requestDecreaseVolume(increment); }
function remoteRequestToggleMute() { if (remote) remote.requestToggleMute(); }
function remoteRequestShuffleMode(mode) { if (remote) remote.requestShuffleMode(mode); }
function remoteRequestLoopMode(mode) { if (remote) remote.requestLoopMode(mode); }
function remoteRequestToggleShuffle() { if (remote) remote.requestToggleShuffle(); }
function remoteRequestToggleLoop() { if (remote) remote.requestToggleLoop(); }
function remoteRequestSeekToPercentage(percentage) { if (remote) remote.requestSeekToPercentage(percentage); }
function remoteRequestPlaylist() { if (remote) remote.requestPlaylist(); }
function remoteRequestBrowse() { if (remote) remote.requestBrowse(); }
function remoteGetIpAddress() { if (remote) return remote.getIpAddress(); }
function remoteRequestTrackById(trackId) { if (remote) remote.requestTrackById(trackId); }
function remoteRequestTrackByPath(path) { if (remote) remote.requestTrackByPath(path); }
function remoteRequestQueueByPath(path) { if (remote) remote.requestQueueByPath(path); }
function remoteRequestClearPlaylist() { if (remote) remote.requestClearPlaylist(); }
function remoteRequestDeleteFromPlaylist(id) { if (remote) remote.requestDeleteFromPlaylist(id); }
